import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:o2oa_all_platform/common/extension/string_extension.dart';
import 'package:table_calendar/table_calendar.dart';

import '../../../common/models/index.dart';
import '../../../common/style/index.dart';
import '../../../common/utils/index.dart';
import '../../../common/widgets/o2_stateless_widget.dart';
import 'index.dart';

class CalendarPage extends GetView<CalendarController> {
  const CalendarPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GetBuilder<CalendarController>(
      builder: (_) {
        return O2UI.basePopScope(
            child: Scaffold(
          appBar: AppBar(title: Obx(()=>Text(controller.state.title)), actions: [
            TextButton(
                onPressed: () => controller.enterCreateEvent(),
                child: Text('calendar_action_create_event'.tr,
                    style: AppTheme.whitePrimaryTextStyle)),
            TextButton(
                onPressed: () => controller.enterCalendarListPage(),
                child: Text('calendar_action_calendar'.tr,
                    style: AppTheme.whitePrimaryTextStyle)),
          ]),
          body: SafeArea(
            child: Column(
              children: [
                calendarView(context),
                Expanded(
                  flex: 1,
                  child: eventListView(context),
                )
              ],
            ),
          ),
        ));
      },
    );
  }

  ///
  /// 日历控件
  ///
  Widget calendarView(BuildContext context) {
    final now = DateTime.now();
    final first = DateTime(now.year - 1, now.month, now.day);
    final end = DateTime(now.year + 1, now.month, now.day);
    var language = 'zh_CN';
    if (Get.locale != null) {
      language = '${Get.locale?.languageCode}_${Get.locale?.countryCode}';
    }
    return Obx(() => TableCalendar<EventInfo>(
          calendarStyle: CalendarStyle(
              markersMaxCount: 1,
              markerDecoration: BoxDecoration(
                color: Theme.of(context).colorScheme.primary,
                shape: BoxShape.circle,
              )),
          headerStyle: const HeaderStyle(
            headerPadding: EdgeInsets.symmetric(horizontal: 8, vertical: 8),
            leftChevronVisible: false,
            rightChevronVisible: false,
          ),
          focusedDay: controller.state.focusedDay,
          firstDay: first,
          lastDay: end,
          locale: language,
          calendarFormat: CalendarFormat.month,
          availableCalendarFormats: {
            CalendarFormat.month: 'meeting_month_view'.tr
          },
          eventLoader: (day) => controller.loadEvent(day),
          onDaySelected: ((selectedDay, focusedDay) =>
              controller.onDaySelected(selectedDay, focusedDay)),
          selectedDayPredicate: (day) {
            return isSameDay(controller.state.selectedDay, day);
          },
          onPageChanged: ((focusedDay) {
            OLogger.d('翻页： ${focusedDay.toLocal()}');
            controller.loadEventFromNet(focusedDay);
          }),
        ));
  }

  Widget eventListView(BuildContext context) {
    return Obx(() => ListView.separated(
        itemBuilder: (context, index) {
          final event = controller.state.eventList[index];
          String time = '';
          if (event.isAllDayEvent == true) {
            time = 'calendar_event_all_day'.tr;
          } else {
            time =
                '${event.startTime?.substring(11, 16)} - ${event.endTime?.substring(11, 16)}';
          }
          return ListTile(
            onTap: () => controller.enterEventUpdate(event),
            leading: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Container(
                    width: 32,
                    height: 16,
                    decoration: BoxDecoration(
                      shape: BoxShape.rectangle,
                      borderRadius: BorderRadius.circular(12), // 调整圆角半径以改变椭圆形状
                      color: event.color?.hexToColor(), // 设置背景颜色
                    ))
              ],
            ),
            trailing: Text(time, style: Theme.of(context).textTheme.bodySmall),
            title: Text(event.title ?? '',
                style: Theme.of(context).textTheme.bodyLarge),
          );
        },
        separatorBuilder: (context, index) => const Divider(height: 1),
        itemCount: controller.state.eventList.length));
  }
}
